local fs = require "nixio.fs"
local util = require "nixio.util"

local running=(luci.sys.call("pidof EmbedThunderManager > /dev/null") == 0)
local button=""
local thunderinfo=""
local tblXLInfo={}

button="<br /><br /><input type=\"button\" class=\"cbi-button\" value=\"Xware Manager\" onclick=\"window.open('http://yuancheng.xunlei.com')\" />&nbsp;&nbsp;<input type=\"button\" class=\"cbi-button\" value=\"Forum\" onclick=\"window.open('http://luyou.xunlei.com/forum-51-1.html')\" />"

if running then
	thunderinfo = luci.sys.exec("wget http://localhost:9000/getsysinfo -O - 2>/dev/null")
	string.gsub(string.sub(thunderinfo, 2, -2),'[^,]+',function(w) table.insert(tblXLInfo, w) end)

	tag_ok=[[<em style="font-size:10px;font-style:normal;font-weight:700;line-height:10px;color:#ffffff;background-color:green;padding:1px 4px;border-radius:4px;-webkit-border-radius:4px;-moz-border-radius:4px;">OK</em>]]

	tag_error=[[<em style="font-size:10px;font-style:normal;font-weight:700;line-height:10px;color:#ffffff;background-color:red;padding:1px 4px;border-radius:4px;-webkit-border-radius:4px;-moz-border-radius:4px;">ERROR</em>]]

	detailInfo = thunderinfo .. [[<br /><br />]]
	if tonumber(tblXLInfo[1]) == 0 then
	  detailInfo = detailInfo .. [[<span>Running ]]..tag_ok..[[</span>  /  ]]
	else
	  detailInfo = detailInfo .. [[<span>Running ]]..tag_error..[[</span>  /  ]]
	end
	
	if tonumber(tblXLInfo[2]) == 0 then
	  detailInfo = detailInfo .. [[<span>Network ]]..tag_error..[[</span>  /  ]]
	else
	  detailInfo = detailInfo .. [[<span>Network ]]..tag_ok..[[</span>  /  ]]
	end
	
	-- if tonumber(tblXLInfo[4]) == 0 then
	--   detailInfo = detailInfo .. [[<span>Unound</span>  /  ]]
	-- else
	--   detailInfo = detailInfo .. [[<span>Bound</span>  /  ]]
	-- end

	if tonumber(tblXLInfo[6]) == 0 then
	  detailInfo = detailInfo .. [[<span>Mount ]]..tag_error..[[</span>  /  ]]
	else
	  detailInfo = detailInfo .. [[<span>Mount ]]..tag_ok..[[</span>  /  ]]
	end

	if string.len(tblXLInfo[5]) > 3 then
		detailInfo = detailInfo .. [[<span>Activation code:]] .. tblXLInfo[5] .. [[</span>]]
	else
		detailInfo = detailInfo .. [[<em style="font-size:10px;font-style:normal;font-weight:700;line-height:10px;color:#ffffff;background-color:black;padding:1px 4px;border-radius:4px;-webkit-border-radius:4px;-moz-border-radius:4px;">BOUND</em>]]
	end

	m = Map("thunder", translate("Xware"), translate("Xware is running") .. button .. "<br /><br /><pre style='font-family:Arial;'>" .. detailInfo .. "</pre>")
else
	m = Map("thunder", translate("Xware"), translate("Xware is not running") .. button)
end

local xware_path=tostring(m.uci:get( "thunder", "config", "file" ))

s = m:section(TypedSection, "thunder")
s.anonymous = true

s:tab("basic",  translate("Basic"))

enable = s:taboption("basic", Flag, "enable", translate("Enable"))
enable.rmempty = false

vod = s:taboption("basic", Flag, "vod", translate("Remove VOD"))
vod.rmempty = false

local devices = {}
util.consume((fs.glob("/mnt/*")), devices)

device = s:taboption("basic", Value, "device", translate("Download Path"))
device.rmempty = false
for i, dev in ipairs(devices) do
	device:value(dev)
end

file = s:taboption("basic", Value, "file", translate("Xware Path"))
for i, dev in ipairs(devices) do
	file:value(dev)
end

model = s:taboption("basic", ListValue, "model", translate("Router Model"),translate("ar71xx: mipseb_32_uclibc"))
model:value("mipseb_32_uclibc")
model:value("mipsel_32_uclibc")
model:value("x86_32_glibc")
model:value("x86_32_uclibc")
model:value("pogoplug")
model:value("armeb_v6j_uclibc")
model:value("armeb_v7a_uclibc")
model:value("armel_v5t_uclibc")
model:value("armel_v5te_android")
model:value("armel_v5te_glibc")
model:value("armel_v6j_uclibc")
model:value("armel_v7a_uclibc")
model:value("asus_rt_ac56u")
model:value("cubieboard")
model:value("iomega_cloud")
model:value("my_book_live")
model:value("netgear_6300v2")

url = s:taboption("basic", Value, "url", translate("Update URL"))
url.rmempty = false
url:value("http://192.168.1.1:88/xware")

version=luci.sys.exec("cat /mnt/843n/Thunder/version 2>/dev/null")

check_update = s:taboption("basic", Button, "_button", translate("Update & Install"))
check_update.inputtitle = translate("Check For Update")
check_update.inputstyle = nil

function check_update.write(self, section, value)
	local update_url = tostring(m.uci:get( "thunder", "config", "url" ))
	local version_lastest = luci.sys.exec("wget -qO- " .. update_url .." 2>/dev/null|grep -o '[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+'|awk 'END{print}'")
	if string.len(version_lastest) > 1 then
		if version == "" then
			update_now.inputtitle = translate("Install")
			check_update.description = translate("Found a new version: ") .. version_lastest
		elseif version == version_lastest then
			update_now.inputtitle = version
			check_update.description = translate("No update were found")
		else
			update_now.inputtitle = translate("Update Now") .. version_lastest
			check_update.description = translate("Found a new version: ") .. version_lastest
		end
	else
		check_update.description = "<span style='color:red'>" .. translate("Failed to get the last version") .. "</span>"
	end
end

update_now = s:taboption("basic", Button, "_update_now", translate("Version"))
update_now.inputstyle = "apply"
if version ~= "" then
	version_info = version
else
	version_info = translate("Install")
end
update_now.inputtitle = version_info

function update_now.write(self, section, value)
    update_now.inputtitle = translate("Please waite ...")
    luci.sys.exec("/etc/init.d/thunder update")
    update_now.inputtitle = version_info
end

-- s:tab("editconf_mounts", translate("Mount"))
-- editconf_mounts = s:taboption("editconf_mounts", Value, "_editconf_mounts", "", translate("Comment by #"))
-- editconf_mounts.template = "cbi/tvalue"
-- editconf_mounts.rows = 20
-- editconf_mounts.wrap = "off"

-- function editconf_mounts.cfgvalue(self, section)
-- 	return fs.readfile(xware_path.."/Thunder/cfg/thunder_mounts.cfg") or ""
-- end
-- function editconf_mounts.write(self, section, value1)
-- 	if value1 then
-- 		value1 = value1:gsub("\r\n?", "\n")
-- 		fs.writefile(xware_path.."/Thunder/cfg/thunder_mounts.cfg", value1)
-- 	end
-- end

s:tab("editconf_etm", translate("Xware"))
editconf_etm = s:taboption("editconf_etm", Value, "_editconf_etm", "", translate("Comment by ;"))
editconf_etm.template = "cbi/tvalue"
editconf_etm.rows = 20
editconf_etm.wrap = "off"

function editconf_etm.cfgvalue(self, section)
	return fs.readfile(xware_path.."/Thunder/cfg/etm.cfg") or ""
end
function editconf_etm.write(self, section, value2)
	if value2 then
		value2 = value2:gsub("\r\n?", "\n")
		fs.writefile(xware_path.."/Thunder/cfg/etm.cfg", value2)
	end
end

s:tab("editconf_download", translate("Download"))
editconf_download = s:taboption("editconf_download", Value, "_editconf_download", "", translate("Comment by ;"))
editconf_download.template = "cbi/tvalue"
editconf_download.rows = 20
editconf_download.wrap = "off"

function editconf_download.cfgvalue(self, section)
	return fs.readfile(xware_path.."/Thunder/cfg/download.cfg") or ""
end
function editconf_download.write(self, section, value3)
	if value3 then
		value3 = value3:gsub("\r\n?", "\n")
		fs.writefile(xware_path.."/Thunder/cfg/download.cfg", value3)
	end
end
return m
